/**
 * 2015，thor.com，all rights reserved。
 * 
 * Project：		redstar-web
 * Filename：	DownloadServlet.java
 * Created：		2015年12月31日
 * Creator：		thor
 */
package com.thor.palmmall.download;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;

import com.thor.palmmall.dao.banlancebill.BanlanceBillDao;
import com.thor.palmmall.rest.balancebill.BanlanceBill;
import com.thor.palmmall.rest.balancebill.CAApiConfig;
import com.thor.util.ApplicationContextUtils;

/**
 * @author thor
 *
 */
public class DownloadServlet extends HttpServlet {
  private static final long serialVersionUID = 1L;

  public static final String SYSTEM_ENCODING = "utf-8";
  public static String ENCODING_CHARSET = SYSTEM_ENCODING;

  protected void doGet(HttpServletRequest request, HttpServletResponse response)
      throws IOException {
    processRequest(request, response);
  }

  protected void doPost(HttpServletRequest request, HttpServletResponse response)
      throws IOException {
    processRequest(request, response);
  }

  private void processRequest(HttpServletRequest request, HttpServletResponse response)
      throws IOException {
    request.setCharacterEncoding(ENCODING_CHARSET);
    String filepath = null;
    String fileName = null;

    if (request.getParameterMap().containsKey("billId")) {
      String billId = request.getParameter("billId");
      BanlanceBillDao banlanceBillDao = ApplicationContextUtils.getBean(BanlanceBillDao.class);
      BanlanceBill bill = banlanceBillDao.get(billId);
      if (bill == null) {
        response.sendError(500, "找不到文件记录。");
        return;
      }
      if(bill != null && !"confirmed".equals(bill.getBillState())){
        response.sendError(500, "对账单未确认");
        return;
      }
      CAApiConfig caApiConfig = ApplicationContextUtils.getBean(CAApiConfig.class);
      filepath =  caApiConfig.getFilePath() + File.separatorChar +bill.getBillSettle() + File.separatorChar + bill.getContract().getCode() + ".pdf";
//      filepath =  "/Users/Luke/Desktop/test" + File.separatorChar + bill.getBillSettle() + File.separatorChar + bill.getContract().getCode() + ".pdf";
      fileName = bill.getContract().getCode() + ".pdf";
    } 
    InputStream in = null;
    try {
      in = new FileInputStream(filepath);
    } catch (FileNotFoundException e) {
      response.sendError(500, "文件不存在。");
      return;
    }

    response.setCharacterEncoding(ENCODING_CHARSET);
    response.setHeader("Content-Type", "charset=" + ENCODING_CHARSET);
    response.setHeader("Content-Disposition", "attachment;filename=" + encodeFileName(fileName));

    BufferedInputStream bis = null;
    BufferedOutputStream bos = null;
    try {
      bis = new BufferedInputStream(in);
      bos = new BufferedOutputStream(response.getOutputStream());
      byte[] buff = new byte[2048];
      int bytesRead;
      while (-1 != (bytesRead = bis.read(buff, 0, buff.length)))
        bos.write(buff, 0, bytesRead);
    } finally {
      if (bis != null)
        bis.close();
      if (bos != null)
        bos.close();
    }
  }

  public static String encodeFileName(String fileName) {
    String s = encodePathInfo(fileName, "utf-8");
    s = s.replaceAll("%2f", "/");
    s = s.replaceAll("%2e", ".");
    return s;
  }

  public static String encodePathInfo(String s, String encodingCharset) {
    StringBuffer stringbuffer = new StringBuffer();
    encodePathInfo(s, stringbuffer, encodingCharset);
    return stringbuffer.toString();
  }

  private static void encodePathInfo(String s, StringBuffer stringbuffer, String encodingCharset) {
    byte abyte0[] = null;
    try {
      abyte0 = s.getBytes(encodingCharset);
    } catch (UnsupportedEncodingException unsupportedencodingexception) {
      return;
    }
    int i = abyte0.length;
    for (int j = 0; j < i; j++) {
      byte byte0 = abyte0[j];
      if (byte0 == 45 || byte0 == 95 || byte0 >= 48 && byte0 <= 57 || byte0 >= 65 && byte0 <= 90
          || byte0 >= 97 && byte0 <= 122) {
        stringbuffer.append((char) byte0);
      } else {
        stringbuffer.append('%');
        byte byte1 = byte0;
        stringbuffer.append("0123456789abcdef".charAt(byte1 >>> 4 & 0xf));
        stringbuffer.append("0123456789abcdef".charAt(byte1 & 0xf));
      }
    }

  }
}
